package org.lxy.config;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.lxy.domain.config.AliyunOssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

//阿里云OSS对象存储工具类
@Configuration
@Slf4j
@Data
public class OSSClientConfig {

    private AliyunOssProperties aliyunOssProperties;

    private CredentialsProvider credentialsProvider;

    private String endPoint;

    private String accessKeyId;

    private String sccessKeySecret;

    private String bucketName;

    private String imageFolder;

    private final long IMAGE_EXPIRE_TIME = 12 * 30 * 24 * 60 * 60 * 1000L;//图片访问链接的过期时间

    private OSSClient ossClient;

    public OSSClientConfig(@Autowired AliyunOssProperties aliyunOssProperties) {
        this.endPoint=aliyunOssProperties.getEndPoint();
        this.accessKeyId=aliyunOssProperties.getAccessKeyId();
        this.sccessKeySecret=aliyunOssProperties.getSccessKeySecret();
        this.bucketName=aliyunOssProperties.getBucketName();
    }

    /**
     * 上传图片获取fileUrl
     * @return
     */
    public String uploadFile2OSS(MultipartFile file) {
        String ret = "";
        if (Objects.isNull(file)  || file.isEmpty()){
            return ret;
        }
        InputStream instream =null ;
        try {
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            String fileName = UUID.randomUUID().toString() + substring;
            instream = file.getInputStream();
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件

            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, sccessKeySecret);
            PutObjectResult putResult = ossClient.putObject(bucketName, fileName, instream, objectMetadata);
            ret = "https://chiaching.oss-cn-beijing.aliyuncs.com/"+fileName+"?versionId="+putResult.getVersionId();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, sccessKeySecret);
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }


    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }


}
